﻿using System;
using System.Windows.Forms;
using QuickTest.Core.Compilation;
using QuickTest.Core.Events;
using QuickTest.Core.TestRunner;

namespace QuickTest.UI.Controls
{
    public partial class OutputTextBox : TextBox
    {
        public OutputTextBox()
        {
            InitializeComponent();
        }

        private void WriteLine(string result)
        {
            if (String.IsNullOrEmpty(result))
                return;

            this.InvokeIfNeeded(() => this.AppendText(result));
            this.InvokeIfNeeded(() => this.AppendText(Environment.NewLine));
        }

        private void ClearText()
        {
            this.InvokeIfNeeded(() => this.Clear());
        }

        public void RegisterEvents(IEventHub eventHub)
        {
            eventHub.TestRunExecuted += eventHub_TestRunExecuted;
            eventHub.CompileStarted += eventHub_CompileStarted;
            eventHub.CompileFinished += eventHub_CompileFinished;
            eventHub.CompileError += eventHub_CompileError;
            eventHub.TestFinished += eventHub_TestFinished;
        }

        private void eventHub_TestRunExecuted(object sender, EventArgs e)
        {
            ClearText();
        }

        private void eventHub_CompileError(object sender, CompileErrorEventArgs e)
        {
            WriteLine(e.Message);
        }

        private void eventHub_CompileFinished(object sender, CompileFinishedEventArgs e)
        {
            WriteLine(e.Message);
        }

        private void eventHub_CompileStarted(object sender, CompilerEventArgs e)
        {
            WriteLine(e.Message);
        }

        private void eventHub_TestFinished(object sender, TestEventArgs e)
        {
            if (!e.Result.IsSuccess)
            {
                WriteLine(e.Result.ToString());
            }
        }
    }
}
